<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="网点编码" prop="branchCode">
        <el-input
          v-model="queryParams.branchCode"
          placeholder="请输入网点编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="网点名称" prop="branchName">
        <el-input
          v-model="queryParams.branchName"
          placeholder="请输入网点名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="网点所在区域" prop="regionId" label-width="100px">
        <treeselect
          v-model="queryParams.regionId"
          :options="pageRegionDataOptions"
          :normalizer="regionNormalizer"
          placeholder="请选择网点所在区域"
          :loadOptions="loadRegionOptions"
          noOptionsText="暂无选项"
          noResultsText="没有匹配的搜索结果"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['items:branch:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['items:branch:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['items:branch:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['items:branch:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="branchList" @selection-change="handleSelectionChange"
      row-key="id"
      lazy
      :load="load"
      ref="table"
      :key="forceUpdateKey"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="网点名称" align="left" prop="branchName" show-overflow-tooltip/>
      <el-table-column label="网点编码" align="center" prop="branchCode"/>
<!--      <el-table-column label="父网点编码" align="center" prop="parentCode"/>-->
      <el-table-column label="网点位置" align="center" prop="address">
        <template slot-scope="scope">
          {{findAncestorsText(scope.row)}}{{scope.row.address}}
        </template>

      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['items:branch:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['items:branch:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      layout="sizes, prev, pager, next, jumper"
    />

    <!-- 添加或修改网点对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" ref="editDialog" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">

        <el-form-item label="父网点" prop="parentCode">
          <treeselect
            class="custom-input-width"
            v-model="form.parentCode"
            :options="copyBranchDataOptions"
            :normalizer="branchNormalizer"
            :show-count="true"
            placeholder="选择父级网点"
            noOptionsText="暂无选项"
            noResultsText="没有匹配的搜索结果"
          />
        </el-form-item>

        <el-form-item label="网点编码" prop="branchCode">
          <el-input v-model="form.branchCode" placeholder="请输入网点编码" :disabled="Boolean(form.id)"/>
        </el-form-item>
        <el-form-item label="网点名称" prop="branchName">
          <el-input v-model="form.branchName" placeholder="请输入网点名称"/>
        </el-form-item>
        <el-form-item label="网点所在区域" prop="ancestors">
          <el-cascader
            style="width: 100%;"
            filterable
            clearable
            v-model="form.ancestors"
            ref="cascader"
            placeholder="请选择网点所在区域"
            :props="elCascaderProps"
            :options="pageRegionDataOptions"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入详细地址信息"/>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listBranch, getBranch, delBranch, addBranch, updateBranch, getChildBranch} from "@/api/items/branch";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "process",
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 网点表格数据
      branchList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        branchCode: null,
        branchName: null,
        regionId: null,
        parentCode: 0
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        branchCode: [
          {required: true, message: "网点编码不能为空", trigger: "blur"}
        ],
        branchName: [
          {required: true, message: "网点名称不能为空", trigger: "blur"}
        ],
        ancestors: [
          {required: true, message: "网点所在区域不能为空", trigger: "change"}
        ],
      },
      pageRegionDataOptions: [],
      // 区域级联选择器配置
      elCascaderProps: {
        value: 'id',
        label: 'name',
        lazy: true,
        lazyLoad() {},
        checkStrictly: true,
        expandTrigger: 'hover'
      },
      //table的key 获取数据时重新渲染表格，解决删除修改懒加载的子节点时刷新有缓存问题
      forceUpdateKey: Math.random(),
    };
  },

  computed: {
    // 网点选项树形数据ancestors.slice
    branchDataOptions() {
      return this.$store.state.device.branchDataOptions || []
    },
    // 所有地区树形数据
    regionDataOptions() {
      return this.$store.state.device.regionDataOptions || []
    },
    // 从vuex复制一份网点选项数据，在最外层加个“无”选项
    copyBranchDataOptions(){
      return [{
        children: this.branchDataOptions,
        branchCode: 0,
        branchName: '无',
      }]
    }
  },
  watch: {
    regionDataOptions: {
      handler(newValue) {
        this.pageRegionDataOptions = newValue.map(item => {
          return {
            ...item,
            children: item.children ? null : undefined,
            leaf: item.children ? false : true,
          }
        })
      },
      immediate: true
    }
  },

  created() {
    this.getList();
    // 区域联动级联选择器懒加载方法设置
    this.elCascaderProps.lazyLoad = ((node, resolve) => {
      // 如果不是第一级区域或者已经存在子区域了，表示已有子节点不需要重新加载，直接resolve()
      if (node.level !== 1 || node.children.length) return resolve();
      node.data.children = this.regionDataOptions.find(item => {
        return item.id === node.value
      }).children;
      resolve();
    })
  },
  mounted() {
    /*在页面渲染完后调用dialog实例，将rendered置为true，提前渲染dialog里面内容，
    解决第一次打开弹窗时，由于里面级联选择器数据过多，渲染导致的延迟问题*/
    this.$refs.editDialog.rendered = true;
  },
  methods: {
    /*根据区域id数组查找对应的中文名称
    @params { Object } row  网点数据信息
    @return { String }  区域中文字符串
    */
    findAncestorsText(row) {
      // 去掉ancestors第一项0，是添加时为了方便后端查询，统一加0，
      let ids = row.ancestors.split(",").slice(1);
      //因为ancestors是不包含最后一级的区域id的，需要在后面加上最后一级的regionId
      ids.push(row.regionId);
      let resultStr = "";
      ids.reduce((prev,currentId)=>{
        const regionItem =  prev.find(item =>{
          if (item.id === currentId){
            resultStr += item.name;
            return true;
          }
          return false;
        });
        return regionItem ? regionItem.children : [];
      },this.regionDataOptions);
      // 返回区域中文
      return resultStr;
    },
    // 区域选项加载下面子区域
    loadRegionOptions({parentNode, callback}) {
      if (parentNode.children && parentNode.children.length) return callback && callback();
      parentNode.children = this.regionDataOptions.find(item => {
        return item.id === parentNode.id
      }).children;
      callback && callback();
    },

    /** 转换分组树形图数据结构 */
    regionNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },

    /** 转换网点树形图数据结构 */
    branchNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.branchCode,
        label: node.branchName,
        children: node.children || undefined,
      };
    },
    // 点击table下拉加载下属区域
    load(tree, treeNode, resolve) {
      const parentCode = tree.branchCode;

      getChildBranch({parentCode}).then(res => {
        const list = res.rows.map(item => {
          return {hasChildren: item.haveChildren === '1', ...item}
        });
        resolve(list)

      })
    },
    /** 查询网点列表 */
    getList() {
      this.loading = true;
      listBranch(this.queryParams).then(response => {
        const list = response.rows.map(item => {
          return {hasChildren: item.haveChildren === '1', ...item}
        });
        this.forceUpdateKey = Math.random();
        this.branchList = list;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        branchCode: null,
        branchName: null,
        parentCode: null,
        regionId: null,
        ancestors: null,
        address: null,
        deptCode: null,
        deptName: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加网点";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBranch(id).then(response => {
        const deviceInfoDialogForm = response.data;
        deviceInfoDialogForm.oldBranchCode = deviceInfoDialogForm.parentCode;

        if (deviceInfoDialogForm.ancestors) {
          try {
            /*把ancestors字符串转为数组,因为在添加的时候统一给ancestors加了父级id0，并且去掉了自身id
            在更新的时候要将最第一级0去掉,在最后面加上自身id */
            deviceInfoDialogForm.ancestors = deviceInfoDialogForm.ancestors.split(",").slice(1);
            deviceInfoDialogForm.ancestors.push(deviceInfoDialogForm.regionId);
          } catch (err) {
            deviceInfoDialogForm.ancestors = [];
            console.log("自动回选地址错误", err)
          }

          // 获取第一级选项数据
          const parentNode = this.pageRegionDataOptions.find(item => {
            return item.id === deviceInfoDialogForm.ancestors[0]
          });

          // 如果该省份不存在子区域数据并且不是最后一级，需要提前添加数据渲染，才能让修改时自动选中区域
          if (parentNode !== undefined && !parentNode.children && !parentNode.leaf) {
            this.loadRegionOptions({parentNode})
          }
        }

        this.form = deviceInfoDialogForm;

        this.open = true;
        this.title = "修改网点信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.branchCode === this.form.parentCode) {
            return  this.$modal.confirmAlert('不允许选自己作为父网点！')
          }
          // 将选中部署区域的祖级id前面统一加0，方便后端查询
          const ancestors = [0, ...this.form.ancestors.slice(0, -1)].join(",");
          // 最后一级的区域id
          const regionId = this.form.ancestors[this.form.ancestors.length - 1];
          const params = Object.assign({}, this.form, {ancestors, regionId});
          if (this.form.id != null) {
            updateBranch(params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              // 重新加载网点数据
              this.$store.dispatch('LoadBranchOptionsTree');
            });
          } else {
            addBranch(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              // 重新加载网点数据
              this.$store.dispatch('LoadBranchOptionsTree');
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('删除网点，会同时级联删除该网点下的所有主题，请确认是否删除？').then(function () {
        return delBranch(ids);
      }).then(() => {
        this.getList();
        // 重新加载网点数据
        this.$store.dispatch('LoadBranchOptionsTree');
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {

      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('items/branch/export', {
        ...this.queryParams
      }, `事项步骤_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .vue-treeselect__control {
  height: 32px;
  width: 215px;
  line-height: 32px !important;
}

.custom-input-width {
  width: 100%;

  ::v-deep .vue-treeselect__control {
    width: 100%;
  }
}
</style>


